﻿/***************************************************************************
 * 文件名：MainForm
 * 功能：
 * 说明： 属性生成器主窗体
 * -------------------------------------------------------------------------
 * 创建时间：2025/7/9 08:50:43
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml;

using Util;
using GridView = DevExpress.XtraGrid.Views.Grid.GridView;
using MessageBox = System.Windows.Forms.MessageBox;

namespace CodeGenerator
{
	public partial class MainForm : XtraForm
	{
		#region Propertys

		private string _sqlConnectString;

		/// <summary>
		/// 当前选择模板名称
		/// </summary>
		private string CurrentTemplateName;

		/// <summary>
		/// 当前选择数据库
		/// </summary>
		private TreeNodeModel CurrentDataBase;

		/// <summary>
		/// 主机连接数据源
		/// </summary>
		private List<TreeNodeModel> HostConfigurationModels = new List<TreeNodeModel>();

		/// <summary>
		/// 可选表列表
		/// </summary>
		private List<TableModel> TableModels = new List<TableModel>();

		/// <summary>
		/// 表中字段显示列表
		/// </summary>
		private List<TableInfoModel> TableInfoModels = new List<TableInfoModel>();

		/// <summary>
		/// 暂存模板数据集合
		/// </summary>
		public ObservableCollection<TemporarilyDataTable> TemporarilyDataTables = new ObservableCollection<TemporarilyDataTable>();

		#endregion

		#region Const

		/// <summary>
		/// 模板文件存放所在文件夹
		/// </summary>
		private const string c_TemplateDirectoryName = "TemplateFile";

		/// <summary>
		/// 模板类型配置文件
		/// </summary>
		private const string c_TemplateConfigurationFileName = "TemplateConfiguration.xml";

		/// <summary>
		/// 属性
		/// </summary>
		private const string c_Property = "Property";

		/// <summary>
		/// 筛选表名
		/// </summary>
		private const string c_Common_Data = "Common.Data.";

		/// <summary>
		/// 主机连接配置文件夹名称
		/// </summary>
		private const string c_Config = "Config";

		/// <summary>
		/// 主机配置文件
		/// </summary>
		private const string c_HostConnectConfiguration = "HostConsfiguration.config";

		#endregion

		#region Win

		public MainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			//加载主机配置
			LoadHostConfiguration();

			///初始化模板配置
			InitTemplateConfiguration();

			//初始化暂存数据显示列
			InitListViewGridColumn();

			repositoryItemCheckEdit1.EditValueChanged += RepositoryItemCheckEdit1_EditValueChanged;
		}

		#endregion

		#region Methods

		#region 加载配置构建树形结构

		/// <summary>
		/// 加载主机连接配置
		/// </summary>
		private void LoadHostConfiguration()
		{
			try
			{
				//检测配置文件是否存在，若不存在则创建此文件
				//若文件存在则读取主机连接配置
				string hostConfiguurationDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_Config);
				string hostConfiguurationFilePath = Path.Combine(hostConfiguurationDir, c_HostConnectConfiguration);

				if (!Directory.Exists(hostConfiguurationDir))
				{
					//创建文件夹
					Directory.CreateDirectory(hostConfiguurationDir);
				}

				//若文件不存在，则创建默认文件
				if (!File.Exists(hostConfiguurationFilePath))
				{
					//创建配置文件
					using (FileStream fs = new FileStream(hostConfiguurationFilePath, FileMode.Create))
					{
						using (StreamWriter writer = new StreamWriter(fs))
						{
							writer.Write(hostConfiguurationFilePath);
						}
					}

					//创建配置文件默认内容
					XmlUtil.GeneratorAppConfig(hostConfiguurationFilePath);
				}
				else //若文件存在则加载配置
				{
					//清空主机连接列表
					HostConfigurationModels?.Clear();

					var list = CodeGeneratorUtil.GetDataBaseConfiguration(hostConfiguurationFilePath);
					if (list?.Count == 0)
					{
						return;
					}

					foreach (var data in list)
					{
						if (string.IsNullOrEmpty(data.HostConnectName) || string.IsNullOrEmpty(data.ConnectString))
						{
							continue;
						}

						//向HostConfigurationModels添加树节点
						GeneratorTreeNode(data.HostConnectName, data.ConnectString);
					}
				}

				//刷新数据源
				treeList1.DataSource = HostConfigurationModels;
				treeList1.RefreshDataSource();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 初始化模板文件配置
		/// </summary>
		private void InitTemplateConfiguration()
		{
			try
			{
				#region 获取模板文件

				//本地文件目录
				string appRunDir = AppDomain.CurrentDomain.BaseDirectory;

				string templateDir = Path.Combine(appRunDir, c_TemplateDirectoryName);

				if (!Directory.Exists(templateDir))
				{
					return;
				}

				#endregion

				#region 获取模板列表

				LoadTemplateConfiguration(Path.Combine(templateDir, c_TemplateConfigurationFileName));

				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 构建树节点
		/// </summary>
		/// <param name="name"></param>
		/// <param name="connectString"></param>
		/// <returns></returns>
		private void GeneratorTreeNode(string name, string connectString)
		{
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(connectString))
			{
				return;
			}

			string parentID = DateTime.Now.ToString("yyyyMMddHHmmssfff");
			HostConfigurationModels.Add(new TreeNodeModel
			{
				ID = parentID,
				Name = name,
				ConnectString = connectString,
				IsRootNode = true,
			});

			//获取当前主机下的所有数据库（除系统数据库外）
			List<string> dataBases = CodeGeneratorUtil.GetAllDataBases(connectString);
			if (dataBases?.Count > 0)
			{
				int i= 0;
				dataBases.ForEach(data =>
				{
					HostConfigurationModels.Add(new TreeNodeModel
					{
						ParentID = parentID,
						ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + i,
						Name = data,
						ConnectString = string.Format("{0};Initial Catalog={1};", connectString, data)
					});
					i++;
				});
			}
		}

		/// <summary>
		/// 获取模板文件配置
		/// </summary>
		/// <returns></returns>
		private void LoadTemplateConfiguration(string templateFilePath = "")
		{
			TemporarilyDataTables?.Clear();

			listBox.DataSource = TemporarilyDataTables;
			listBox.DisplayMember = "FileMame";
			listBox.ValueMember = "FileMame";

			try
			{
				if (string.IsNullOrEmpty(templateFilePath))
				{
					templateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_TemplateDirectoryName, c_TemplateConfigurationFileName);
				}

				if (!File.Exists(templateFilePath))
				{
					return;
				}

				XmlDocument doc = new XmlDocument();
				doc.Load(templateFilePath);
				if (doc == null)
				{
					return;
				}

				// 读取节点
				XmlNode root = doc.DocumentElement;
				if (root?.ChildNodes?.Count == 0)
				{
					return;
				}

				string templateDir = Path.GetDirectoryName(templateFilePath);

				foreach (XmlNode childNode in root.ChildNodes)
				{
					if (childNode == null) { continue; }
					string fileName = childNode.Attributes["Name"].Value;
					string filePath = childNode.Attributes["Value"].Value;
					string optionFileName = childNode.Attributes["OptionFile"].Value;
					if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(filePath))
					{
						continue;
					}

					//检测模板文件是否存在
					if (!File.Exists(Path.Combine(templateDir, filePath)))
					{
						continue;
					}

					//构造数据
					var temporarily = new TemporarilyDataTable()
					{
						FileMame = fileName,
						FilePath = filePath,
						OptionFileName = optionFileName,
						TemplateDataTable = new DataTable()
					};

					//初始化DataTable字段
					InitDataTableColumns(temporarily);

					//添加
					TemporarilyDataTables.Add(temporarily);

					//绑定数据
					listBox.DataSource = TemporarilyDataTables;

					//默认设置第一行数据
					listBox.SetSelected(0, true);
					labTemplateName.Text = CurrentTemplateName = TemporarilyDataTables.FirstOrDefault().FileMame;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 构建数据库连接字符串
		/// 查找当前选择的数据库中的表
		/// </summary>
		private void BuildDataBaseConnectionString(bool isRootNode,string connectString )
		{
			try
			{
				_sqlConnectString = isRootNode ? "" : connectString;

				//查找当前选择的数据库中的表
				InitTableModels();

				TableInfoModels?.Clear();
				txtGeneratorResult.Text = string.Empty;
				TemporarilyDataTables?.ToList().ForEach(data =>
				{
					data.TemplateDataTable?.Rows?.Clear();
				});
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region 数据表操作方法

		/// <summary>
		/// 初始化DataTable
		/// </summary>
		/// <param name="temporarily"></param>
		private void InitDataTableColumns(TemporarilyDataTable temporarily)
		{
			try
			{
				#region 清空数据

				if (temporarily == null)
				{
					return;
				}

				if (temporarily.TemplateDataTable == null)
				{
					temporarily.TemplateDataTable = new DataTable();
				}

				#endregion

				#region 添加默认字段

				var dataTable = temporarily.TemplateDataTable;

				//表名
				dataTable.Columns.Add(new CustomDataColumn
				{
					Caption = "表名",
					DataType = typeof(string),
					ColumnName = "TableName",
					Width = 150
				});

				//字段名称
				dataTable.Columns.Add(new CustomDataColumn
				{
					Caption = "列名",
					DataType = typeof(string),
					ColumnName = "FieldName",
					Width = 150
				});

				//描述信息
				dataTable.Columns.Add(new CustomDataColumn
				{
					Caption = "描述信息",
					DataType = typeof(string),
					ColumnName = "FieldText",
					Width = 150
				});

				//类型
				dataTable.Columns.Add(new CustomDataColumn
				{
					Caption = "类型",
					DataType = typeof(string),
					ColumnName = "Type",
					Width = 10
				});

				#endregion

				#region 从配置中读取可配置字段

				//检测可选属性配置文件是否存在，若不存在则return
				string propertyConfigurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_TemplateDirectoryName, temporarily.OptionFileName);
				if (string.IsNullOrEmpty(propertyConfigurationFilePath) || !File.Exists(propertyConfigurationFilePath))
				{
					return;
				}

				//读取配置
				XmlDocument doc = new XmlDocument();
				doc.Load(propertyConfigurationFilePath);
				if (doc == null)
				{
					return;
				}

				XmlElement root = doc.DocumentElement;
				if (root == null || root?.ChildNodes?.Count == 0)
				{
					return;
				}

				foreach (XmlNode childNode in root.ChildNodes)
				{
					if (childNode == null) { continue; }
					string columnHeader = childNode.Attributes["Name"].Value;
					string columnName = childNode.Attributes["Value"].Value;
					string width = childNode.Attributes["Width"].Value;
					if (string.IsNullOrEmpty(columnHeader) || string.IsNullOrEmpty(columnName))
					{
						continue;
					}

					//添加至Columns
					dataTable.Columns.Add(new CustomDataColumn()
					{
						Caption = columnHeader,
						DataType = typeof(bool),
						ColumnName = columnName,
						Width = string.IsNullOrEmpty(width) ? 70 : Convert.ToInt16(width),
						DefaultValue = false
					});
				}

				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 添加DataTable数据行
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="column"></param>
		/// <param name="dText"></param>
		private void AddDataTableRow(DataTable dataTable, string tableName, string column, string dText, string type)
		{
			try
			{
				DataRow row = dataTable.NewRow();
				row["TableName"] = tableName;
				row["FieldName"] = column;
				row["FieldText"] = dText;
				row["Type"] = type;

				if (dataTable.Columns.Contains("IsSimpleProperty"))
				{
					row["IsSimpleProperty"] = true;
				}

				dataTable.Rows.Add(row);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 删除DataTable数据行
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="column"></param>
		/// <param name="dText"></param>
		private void DeleteDataTableRow(DataTable dataTable, string tableName, string column)
		{
			try
			{
				if (dataTable?.Rows == null)
				{
					return;
				}

				//删除数据源里的数据
				DataRow[] rows = dataTable.Select($"TableName = '{tableName}' and FieldName = '{column}' ");
				if (rows?.Count() == 0)
				{
					return;
				}

				for (int i = 0; i < rows.Length; i++)
				{
					dataTable.Rows.Remove(rows[i]);
				}

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 获取数据库中所有表
		/// </summary>
		private void InitTableModels(bool isClear = false)
		{
			try
			{
				//清空表
				TableModels.Clear();
				if (!isClear)
				{
					TableModels.AddRange(CodeGeneratorUtil.GetTableModels(_sqlConnectString).OrderBy(p => p.TableName));
				}

				gridTable.DataSource = TableModels;
				gridTable.MainView.RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 清空可选字段列表和暂存数据
		/// </summary>
		private void ClearOptionColumnAndTemporarilyStoreData()
		{
			TableInfoModels.Clear();
			gridOptionColumn.DataSource = TableInfoModels;
			gridOptionColumn.MainView.RefreshData();

			TemporarilyDataTables.ToList().ForEach(data => { data?.TemplateDataTable?.Rows.Clear(); });
			var temporarilys = TemporarilyDataTables?.Where(p => p.FileMame == CurrentTemplateName);
			if (temporarilys?.Count() > 0)
			{
				DataTable temporarilyDataTable = temporarilys.FirstOrDefault().TemplateDataTable;
				gridAuto.DataSource = temporarilyDataTable;
				gridAuto.MainView.RefreshData();
			}

			txtGeneratorResult.Text = string.Empty;
		}

		/// <summary>
		/// 暂存表字段至生成列表
		/// </summary>
		/// <param name="model"></param>
		public void TemporarilyStoreTableInfo(TableInfoModel model)
		{
			try
			{
				if (model == null)
				{
					return;
				}

				var temporarilys = TemporarilyDataTables.Where(p => p.FileMame == CurrentTemplateName);
				if (temporarilys?.Count() == 0)
				{
					return;
				}

				var dataTable = temporarilys.FirstOrDefault().TemplateDataTable;
				if (dataTable == null)
				{
					return;
				}

				DataRow[] rows = dataTable.Select($"TableName = '{model.TableName}' and FieldName = '{model.FieldName}'");

				bool isExist = rows?.Count() > 0;

				//如果是选中状态，检测暂存中是否存在此字段，若不存在则直接添加，存在则默认不处理
				if (model.IsSelect && !isExist)
				{
					AddDataTableRow(dataTable, model.TableName, model.FieldName, model.FieldText, model.Type);
				}
				else if (!model.IsSelect && isExist)
				{
					DeleteDataTableRow(dataTable, model.TableName, model.FieldName);
				}

				//刷新数据
				gridAuto.DataSource = dataTable;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 设置选中状态
		/// </summary>
		public void SetTableFieldSelect()
		{
			try
			{
				if(listBox.SelectedItem == null)
				{
					return;
				}

				var selectItem = listBox.SelectedItem as TemporarilyDataTable;
				if (selectItem == null)
				{
					return;
				}

				var temporarilys = TemporarilyDataTables.Where(p => p.FileMame == selectItem.FileMame);
				if (temporarilys?.Count() == 0)
				{
					return;
				}

				var dataTable = temporarilys.FirstOrDefault().TemplateDataTable;
				if (dataTable == null)
				{
					return;
				}
				
				//刷新暂存列表数据

				gridAuto.DataSource = dataTable;

				if (dataTable?.Rows.Count == 0)
				{
					checkBoxColumn.Tag = "0";
					TableInfoModels.ToList().ForEach(data => { data.IsSelect = false; });
					gridOptionColumn.DataSource = TableInfoModels;
					gridOptionColumn.MainView.RefreshData();

					return;
				}

				var list = new List<TableInfoModel>();
				foreach (DataRow data in dataTable?.Rows)
				{
					if (data == null) { continue; }
					list.Add(new TableInfoModel
					{
						TableName = data["TableName"] == null ? "" : data["TableName"].ToString(),
						FieldName = data["FieldName"] == null ? "" : data["FieldName"].ToString(),
					});
				}
				if (list?.Count == 0 || TableInfoModels?.Count == 0)
				{
					return;
				}

				//遍历设置选中状态
				var optionList = TableInfoModels.Where(p => list.Any(u => u.TableName == p.TableName
													  && u.FieldName == p.FieldName));

				if (optionList?.Count() == 0)
				{
					TableInfoModels.ToList().ForEach(data => data.IsSelect = false);
					checkBoxColumn.Tag = "0";
				}
				else
				{
					foreach (var data in TableInfoModels)
					{
						data.IsSelect = optionList.Any(p => p.TableName == data.TableName && p.FieldName == data.FieldName);
					}

					//刷新全选状态
					var gridView = gridTable.MainView as GridView;
					if (gridView == null)
					{
						return;
					}

					var selectTable = gridView.GetFocusedRow() as TableModel;
					if (selectTable == null)
					{
						return;
					}

					if (list.Where(p => p.TableName == selectTable.TableName).Count() == TableInfoModels?.Count())
					{
						checkBoxColumn.Tag = "1";
					}
				}

				//刷新可选字段列表视图
				gridOptionColumn.DataSource = TableInfoModels;
				gridOptionColumn.MainView.RefreshData();

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 创建生成代码模型类
		/// </summary>
		/// <param name="row"></param>
		/// <param name="isStartField"></param>
		/// <param name="isEndField"></param>
		/// <returns></returns>
		private ColumnInfoModel CreateTableInfoModel(DataTable datatable, DataRow row, bool isStartField = false, bool isEndField = false)
		{
			string tableName = row["FieldName"] == null ? "" : row["FieldName"].ToString();
			string originalMame = row["FieldName"] == null ? "" : row["FieldName"].ToString();
			string fieldName = row["FieldName"] == null ? "" : row["FieldName"].ToString();
			string fieldText = row["FieldText"] == null ? "" : row["FieldText"].ToString();


			bool isLoadProperty = datatable.Columns.Contains("IsLoadProperty") &&
													  (row["IsLoadProperty"] == null ? false : Convert.ToBoolean(row["IsLoadProperty"]));
			bool isSetProperty = datatable.Columns.Contains("IsLoadProperty") &&
													  (row["IsSetProperty"] == null ? false : Convert.ToBoolean(row["IsLoadProperty"]));

			if (isStartField || isEndField)
			{
				fieldName = string.Format("{0}{1}", fieldName, isStartField ? UpperAndLowerLimitsConst.Start : UpperAndLowerLimitsConst.End);
				fieldText = string.Format("{0}{1}", fieldText, isStartField ? UpperAndLowerLimitsConst.GetName(UpperAndLowerLimitsConst.Start)
																			: UpperAndLowerLimitsConst.GetName(UpperAndLowerLimitsConst.End));
			}

			return new ColumnInfoModel
			{
				TableName = tableName,
				OriginalFileName = originalMame,
				FieldName = fieldName,
				FieldText = fieldText,
				LoadAndSetProperty = isLoadProperty ? "LoadProperty" : (isSetProperty ? "SetProperty" : "LoadProperty"),
				PropertyName = string.Format("{0}{1}", fieldName, c_Property),
				FilterTableName = string.Format("{0}{1}", c_Common_Data, tableName),
				Type = row["Type"] == null ? "" : row["Type"].ToString(),
			};
		}

		#endregion

		#region 初始化暂存视图

		/// <summary>
		/// 初始化GridView2的GridColumn
		/// </summary>
		private void InitListViewGridColumn()
		{
			try
			{
				if(gridView2 == null)
				{
					return;
				}

				gridView2.Columns?.Clear();

				var selectRow = listBox.SelectedItem as TemporarilyDataTable;
				if(selectRow == null)
				{
					return;
				}

				var columns = selectRow.TemplateDataTable?.Columns;
				if (columns?.Count == 0)
				{
					return;
				}

				int i = 0;
				foreach (CustomDataColumn column in columns)
				{
					if (column == null || column.ColumnName.Equals("Type")) { continue; }

					bool isReadonly = true;

					GridColumn gridColumn = new GridColumn() 
					{ 
						Name = column.ColumnName,
						Caption = column.Caption,
						FieldName = column.ColumnName,
						Width = column.Width,
						Visible = true,
						VisibleIndex = i
					};

					if (column.DataType == typeof(bool))
					{
						isReadonly = false;
						gridColumn.ColumnEdit = new RepositoryItemCheckEdit();
					}
					else if (column.DataType == typeof(string))
					{
						gridColumn.ColumnEdit = new RepositoryItemTextEdit();
					}

					gridColumn.OptionsFilter.AllowFilter = false;
					gridColumn.OptionsColumn.AllowEdit = !isReadonly;
					gridColumn.OptionsColumn.ReadOnly = isReadonly;

					gridView2.Columns.Add(gridColumn);
					i++;
				}
				gridAuto.MainView.RefreshData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#endregion

		#region Event

		/// <summary>
		/// 新建连接
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnConnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			try
			{
				List<string> nameList = HostConfigurationModels?.Select(x => x.Name).ToList();

				FMHostConnnect form = new FMHostConnnect(nameList);
				// 显示模态窗口
				DialogResult dialogResult = form.ShowDialog();
				if(dialogResult!= DialogResult.OK)
				{
					return;
				}

				string name = form.ConnnectName;
				string connectString = form.ConnectString;

				if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(connectString))
				{
					return;
				}

				string hostConfiguurationDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_Config);
				string hostConfiguurationFilePath = Path.Combine(hostConfiguurationDir, c_HostConnectConfiguration);

				//增加到配置中
				XmlUtil.AddConnectionStrings(hostConfiguurationFilePath, name, connectString);

				//添加至界面展示
				 GeneratorTreeNode(name, connectString);

				//刷新数据源
				bsDataTreeList.DataSource = HostConfigurationModels;
				treeList1.RefreshDataSource();

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		
		/// <summary>
		/// 删除连接
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			try
			{
				if (treeList1.FocusedNode == null)
				{
					return;
				}
				TreeNodeModel model = treeList1.GetDataRecordByNode(treeList1.FocusedNode) as TreeNodeModel;
				if (model == null )
				{
					return;
				}

				if (!model.IsRootNode)
				{
					MessageBox.Show("当前选择的数据为数据库,请选择连接！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				if (MessageBox.Show($"是否确认删除[{model.Name}]!", "是否确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information) != DialogResult.Yes)
				{
					return;
				}

				//移除数据
				HostConfigurationModels.Remove(model);
				var list = HostConfigurationModels.Where(p => p.ParentID.Equals(model.ID)).ToList();
				if (list?.Count > 0)
				{
					list.ForEach(data => HostConfigurationModels.Remove(data));
				}

				treeList1.DataSource = HostConfigurationModels;
				treeList1.RefreshDataSource();

				string hostConfiguurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, c_Config, c_HostConnectConfiguration);
				if (!File.Exists(hostConfiguurationFilePath))
				{
					return;
				}

				//删除配置
				XmlUtil.DeleteConnectString(hostConfiguurationFilePath, model.Name);

				//检测删除的连接与当前选择的连接一致，则清空数据
				InitTableModels(true);

				//清空可选字段列表和暂存数据
				ClearOptionColumnAndTemporarilyStoreData();

				MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 生成代码
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnGeneratoeCode_Click(object sender, EventArgs e)
		{
			try
			{
				var temporarilys = TemporarilyDataTables?.Where(p => p.FileMame == CurrentTemplateName);
				if (temporarilys?.Count() == 0)
				{
					return;
				}

				var temporarily = temporarilys.FirstOrDefault();

				DataTable temporarilyDataTable = temporarily.TemplateDataTable;

				if (temporarilyDataTable?.Rows?.Count == 0)
				{
					return;
				}

				var model = new TemplateModel
				{
					TemplateFileName = temporarily.FilePath,
					SimplePropertyModels = new List<ColumnInfoModel>(),
					BusinessPropertyModels = new List<ColumnInfoModel>(),
					FilterPropertyModels = new List<ColumnInfoModel>(),
					AllPropertyModels = new List<ColumnInfoModel>(),
				};

				//检测是否存在上下限属性
				#region 属性模板构建数据源

				var upperAndLowerLimitsList = new List<DataRow>();
				bool isExistupperAndLowerLimits = false;

				bool isExistUpperAndUpperLimits = temporarilyDataTable.Columns.Contains("IsUpperAndLowerLimits");
				bool isExistSimpleProperty = temporarilyDataTable.Columns.Contains("IsSimpleProperty");
				bool isExistFilterProperty = temporarilyDataTable.Columns.Contains("IsFilterProperty");
				bool isExistBusinessProperty = temporarilyDataTable.Columns.Contains("IsBusinessProperty");

				if (isExistUpperAndUpperLimits)
				{
					upperAndLowerLimitsList = temporarilyDataTable.Select($"IsUpperAndLowerLimits = true ").ToList();
					isExistupperAndLowerLimits = upperAndLowerLimitsList?.Count > 0;
				}

				//简单属性列表
				if (isExistSimpleProperty)
				{
					string queryString = "IsSimpleProperty = true ";
					if (isExistUpperAndUpperLimits)
					{
						queryString += "and IsUpperAndLowerLimits = false";
					}
					if (isExistBusinessProperty)
					{
						queryString += " and IsBusinessProperty = false";
					}
					if (isExistFilterProperty)
					{
						queryString += " and IsFilterProperty = false";
					}

					var simplePropertyList = temporarilyDataTable.Select(queryString).ToList();
					if (simplePropertyList?.Count() > 0)
					{
						simplePropertyList.ForEach(data =>
						{
							model.SimplePropertyModels.Add(CreateTableInfoModel(temporarilyDataTable, data));
						});
					}
				}

				//业务属性列表
				if (isExistBusinessProperty)
				{
					string queryString = "IsBusinessProperty = true ";
					if (isExistUpperAndUpperLimits)
					{
						queryString += "and IsUpperAndLowerLimits = false";
					}

					if (isExistFilterProperty)
					{
						queryString += " and IsFilterProperty = false";
					}

					var businessPropertyList = temporarilyDataTable.Select(queryString).ToList();
					if (businessPropertyList?.Count > 0)
					{
						businessPropertyList.ForEach(data =>
						{
							model.BusinessPropertyModels.Add(CreateTableInfoModel(temporarilyDataTable, data));
						});
					}
				}

				//筛选属性列表
				if (isExistFilterProperty)
				{
					string queryString = "IsFilterProperty = true ";
					if (isExistUpperAndUpperLimits)
					{
						queryString += "and IsUpperAndLowerLimits = false";
					}

					var filterPropertyList = temporarilyDataTable.Select(queryString).ToList();
					if (filterPropertyList?.Count > 0)
					{
						filterPropertyList.ForEach(data =>
						{
							model.FilterPropertyModels.Add(CreateTableInfoModel(temporarilyDataTable, data));
						});
					}
				}

				//添加上下限数据
				if (isExistupperAndLowerLimits)
				{
					foreach (var data in upperAndLowerLimitsList)
					{
						if (data == null) { continue; }

						List<ColumnInfoModel> list = new List<ColumnInfoModel>();

						//添加上限数据
						list.Add(CreateTableInfoModel(temporarilyDataTable, data, true, false));
						//添加下限数据
						list.Add(CreateTableInfoModel(temporarilyDataTable, data, false, true));

						bool isSimpleProperty = isExistSimpleProperty && (data["IsSimpleProperty"] == null ? false : Convert.ToBoolean(data["IsSimpleProperty"]));
						bool isBusinessProperty = isExistBusinessProperty && (data["IsBusinessProperty"] == null ? false : Convert.ToBoolean(data["IsBusinessProperty"]));
						bool isFilterProperty = isExistFilterProperty && (data["IsFilterProperty"] == null ? false : Convert.ToBoolean(data["IsFilterProperty"]));

						if (isSimpleProperty && !isBusinessProperty && !isFilterProperty)
						{
							model.SimplePropertyModels.AddRange(list);
						}
						else if (isBusinessProperty && !isFilterProperty)
						{
							model.BusinessPropertyModels.AddRange(list);
						}
						else if (isFilterProperty)
						{
							model.FilterPropertyModels.AddRange(list);
						}
					}
				}

				#endregion

				#region DAL模板构建数据源

				for (int i = 0; i < temporarilyDataTable.Rows.Count; i++)
				{
					var data = temporarilyDataTable.Rows[i];
					if (data == null)
					{
						continue;
					}

					string fieldName = data["FieldName"] == null ? "" : data["FieldName"].ToString();

					model.AllPropertyModels.Add(new ColumnInfoModel
					{
						FieldName = string.Format("{0}{1}", fieldName, i < temporarilyDataTable.Rows.Count - 1 ? "," : ""),
					});
				}

				#endregion

				//生成模板代码
				txtGeneratorResult.Text = CodeGeneratorUtil.GeneratorTemlplateCode(model);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 复制
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnCopy_Click(object sender, EventArgs e)
		{
			try
			{
				if (string.IsNullOrEmpty(txtGeneratorResult.Text))
				{
					return;
				}

				//将结果复制到粘贴板
				Clipboard.SetText(txtGeneratorResult.Text);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 刷新表结构
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void simpleButton1_Click(object sender, EventArgs e)
		{
			try
			{
				//重置表结构列表
				InitTableModels();

				///清空可选列表
				ClearOptionColumnAndTemporarilyStoreData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#region 切换表

		/// <summary>
		/// 表结构双击展示表中字段
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridControl3_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			try
			{
				var gridview = gridTable.MainView as GridView;
				if (gridview == null)
				{
					return;
				}

				//获取当前选中行
				var tableInfoModel = gridview.GetFocusedRow() as TableModel;
				if (tableInfoModel == null)
				{
					return;
				}

				//检测可选字段列表中是否与当前选择的表一致，若一致则不清空重新添加
				if (TableInfoModels.Any(p => p.TableName.Equals(tableInfoModel.TableName)))
				{
					return;
				}

				//清空可选字段列表
				TableInfoModels.Clear();
				//获取当前表中所有字段
				CodeGeneratorUtil.GetTableInfoModels(tableInfoModel.TableName, _sqlConnectString).ToList().ForEach(model =>
				{
					TableInfoModels.Add(new TableInfoModel
					{
						TableName = model.TableName,
						FieldName = model.FieldName,
						FieldText = model.FieldText,
						Type = model.Type
					});
				});

				gridOptionColumn.DataSource = TableInfoModels;
				gridOptionColumn.MainView.RefreshData();

				//设置选中状态
				SetTableFieldSelect();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region 切换模板

		/// <summary>
		/// 模板选择改变事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>

		/// <summary>
		/// 双击切换模板
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void listBox_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			try
			{
				if (listBox.SelectedItem == null)
				{
					return;
				}

				var data = listBox.SelectedItem as TemporarilyDataTable;
				if (data == null || data.FileMame.Equals(CurrentTemplateName)) { return; }

				labTemplateName.Text = CurrentTemplateName = data.FileMame;

				//重置列
				InitListViewGridColumn();

				//切换模板后检测是否清空当前可选列选中状态
				SetTableFieldSelect();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region 树节点选择事件

		/// <summary>
		/// 双击加载表结构
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void treeList1_DoubleClick(object sender, EventArgs e)
		{
			if (treeList1.FocusedNode == null)
			{
				return;
			}
			try
			{
				TreeNodeModel model = treeList1.GetDataRecordByNode(treeList1.FocusedNode) as TreeNodeModel;
				if (model == null || model.IsRootNode || model.ID.Equals(CurrentDataBase?.ID))
				{
					return;
				}

				CurrentDataBase = model;

				//非根节点
				BuildDataBaseConnectionString(false, model.ConnectString);

				//获取当前选择的数据库中的表
				InitTableModels();

				//清空可选字段列表和暂存数据
				ClearOptionColumnAndTemporarilyStoreData();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region 选择全部

		private Rectangle checkBoxColumnHeaderRect = Rectangle.Empty;
		private GridColumn checkBoxColumn = null;

		/// <summary>
		/// 自定义列头绘制事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
		{
			if (e.Column != null && e.Column.AbsoluteIndex == 0)
			{
				checkBoxColumnHeaderRect = e.Bounds;
				checkBoxColumn = e.Column;

				//须把列头标题设置为空
				e.Painter.DrawObject(e.Info);

				//在列头中心显示复选框
				int x = e.Bounds.X + (int)((e.Bounds.Width - CheckBoxRenderer.GetGlyphSize(e.Graphics, CheckBoxState.UncheckedNormal).Width) * 0.5);
				int y = e.Bounds.Y + (int)((e.Bounds.Height - CheckBoxRenderer.GetGlyphSize(e.Graphics, CheckBoxState.UncheckedNormal).Height) * 0.5);
				Point location = new Point(x, y);

				CheckBoxState checkBoxState;
				if (e.Column.Tag != null && e.Column.Tag.ToString() == "1")
					checkBoxState = CheckBoxState.CheckedPressed;
				else
					checkBoxState = CheckBoxState.UncheckedNormal;

				CheckBoxRenderer.DrawCheckBox(e.Graphics, location, checkBoxState);

				e.Handled = true;
			}
		}

		/// <summary>
		/// 鼠标抬起事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridView1_MouseUp(object sender, MouseEventArgs e)
		{
			if (checkBoxColumnHeaderRect != Rectangle.Empty)
			{
				if (e.X > checkBoxColumnHeaderRect.X && e.X < (checkBoxColumnHeaderRect.X + checkBoxColumnHeaderRect.Width) && e.Y > checkBoxColumnHeaderRect.Y && e.Y < (checkBoxColumnHeaderRect.Y + checkBoxColumnHeaderRect.Height))
				{
					bool isSelect = false;
					if (checkBoxColumn.Tag != null && checkBoxColumn.Tag.ToString() == "1")
					{
						checkBoxColumn.Tag = "0";
					}
					else
					{
						checkBoxColumn.Tag = "1";
						isSelect = true;
					}

					if (TableInfoModels != null && TableInfoModels.Count > 0)
					{
						foreach (var item in TableInfoModels)
						{
							item.IsSelect = isSelect;
							TemporarilyStoreTableInfo(item);
						}
					}
					gridOptionColumn.DataSource = TableInfoModels;
					gridOptionColumn.RefreshDataSource();
					gridView1.InvalidateColumnHeader(checkBoxColumn);
				}
			}
		}

		/// <summary>
		/// 可选字段列表选择列选中事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void RepositoryItemCheckEdit1_EditValueChanged(object sender, EventArgs e)
		{
			// 使用BeginInvoke延迟执行，确保UI操作完成
			this.BeginInvoke(new Action(() =>
			{
				gridView1.CloseEditor();
				gridView1.UpdateCurrentRow();

				// 获取当前行数据
				var model = gridView1.GetFocusedRow() as TableInfoModel;
				if (model == null)
				{
					return;
				}

				TemporarilyStoreTableInfo(model);
			}));
		}

		#endregion

		#region 暂存数据列表右键菜单事件

		/// <summary>
		/// 暂存数据列表右键弹出事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void gridView2_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
		{
			// 检查是否是右键点击
			if (e.HitInfo.InRowCell)
			{
				// 显示您的 ContextMenuStrip
				contextMenuStrip1.Show(Cursor.Position);
			}
		}

		/// <summary>
		/// 删除选中数据
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnDeleteData_Click(object sender, EventArgs e)
		{
			try
			{
				var gridView = gridAuto.MainView as GridView;
				if (gridView == null)
				{
					return;
				}

				var data = gridView.GetFocusedRow() as DataRowView;
				if (data == null)
				{
					return;
				}

				var temporarilys = TemporarilyDataTables.Where(p => p.FileMame == CurrentTemplateName);
				if (temporarilys?.Count() == 0)
				{
					return;
				}

				var dataTable = temporarilys.FirstOrDefault().TemplateDataTable;
				if (dataTable?.Rows.Count == 0)
				{
					return;
				}

				TableInfoModel model = new TableInfoModel
				{
					TableName = data.Row[0].ToString(),
					FieldName = data.Row[1].ToString(),
				};

				DataRow[] rows = dataTable.Select($"TableName = '{model.TableName}' and FieldName = '{model.FieldName}'");

				bool isExist = rows?.Count() > 0;
				if (isExist)
				{
					for (int i = 0; i < rows.Length; i++)
					{
						dataTable.Rows.Remove(rows[i]);
					}
				}

				gridAuto.DataSource = dataTable;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// 清除全部
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>

		private void btnClearAllData_Click(object sender, EventArgs e)
		{
			try
			{
				var temporarilys = TemporarilyDataTables.Where(p => p.FileMame == CurrentTemplateName);
				if (temporarilys?.Count() == 0)
				{
					return;
				}

				var dataTable = temporarilys.FirstOrDefault().TemplateDataTable;

				if (dataTable?.Rows.Count == 0)
				{
					return;
				}

				///清空列表数据
				dataTable.Rows.Clear();

				gridAuto.DataSource = dataTable;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#endregion

	}
}
